/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

$(function () {
    //var inWexin = Magiclamp.inWeixin();
    //if (inWexin) {
    //   Magiclamp.mcAlert('', '请用其他扫码工具，或者用浏览器打开！');      
    //}

    var wx_has_ready = false;
    var html_data = {
        baseConfig: baseConfig,
        sessionid: '',
        sessionid_q: '',
        show_video_img: true,
        show_video_div: true,
        show_share_bar: false,
        cart_num: 0,
        selected_img:"http://www.mmggoo.com/static/weixin/img2/icon.png",
        send_address: '',
        pro_user_id: GetQueryString("pro_user_id"),
        send_price: 0,
        is_send: false,
        page_index: 0,
        page_count: 1,
        goods_list: [],
        together_goods_info: {},
        start_list:[{type:1, index:0},{type:1, index:1},{type:1, index:2},{type:1, index:3},{type:1, index:4}],
        goods_info: {files_json: []},
        is_login: false
    };
    var app = new Vue({
        el: '#goodsapp',
        data: html_data,
        methods: {
            price_filter: price_filter,
            add_cart: function ($event) {
                if (html_data.is_login) {
                    Magiclamp.midLoadingShow('加入中...');
                    api.lgoods.create_cart({
                        goods_id: html_data.goods_info.id,
                        num: parseInt($("#count-sum").html())
                    }).then(function (data) {
                        Magiclamp.midLoadingHide();
                        Magiclamp.midToast('success', data.message, function () {
                            var _this = $($event);
                            _this.css('pointer-events', 'auto');
                        });
                        app.get_cart_goods_num();
                    }, function (data) {
                        Magiclamp.midLoadingHide();
                        Magiclamp.midToast('fail', '加入失败，请重试', function () {
                            var _this = $($event);
                            _this.css('pointer-events', 'auto');
                        });
                    });
                } else {
                    login_mogu(function () {
                        html_data.is_login = true;
                        app.get_cart_goods_num();
                    }, "goods", GetQueryString("goods_id"), true);
                }

            },
            show_zonghe_pingjia:function(goods){
                window.location.href="goods_friend_comment_list.html?goods_id="+goods.id;
            },
            chat_to_host: function () {
                client_storage("page", "tab_program");
                client_storage("current_imusername", html_data.goods_info.user__imusername);

                client_storage("goods_id", html_data.goods_info.id);
                if(html_data.goods_info.goodsstore_id){
                    client_storage("current_realname", html_data.goods_info.goodsstore__name);
                    client_storage("goodsstore_id", html_data.goods_info.goodsstore_id);
                }else{
                    client_storage("goodsstore_id", 0);
                    client_storage("current_realname", html_data.goods_info.user__realname);
                }

                window.location.href="home.html"

            },
            get_cart_goods_num: function () {
                api.lgoods.get_cart_goods_num().then(function (data) {
                    html_data.cart_num = data.result;
                    // 记录直接购买的记录
                    var from = GetQueryString("frompage");
                    if(from=="news_share_link"){
                        api.an.save_news_order({goods_id:GetQueryString("goods_id"), news_id:GetQueryString("news_id")}).then(function () {
                            console.log("保存链接进入购买记录")
                        })
                    }else if(from=="goods_share_link"){
                        api.an.save_goods_order({goods_id:GetQueryString("goods_id")}).then(function () {
                            console.log("保存链接进入购买记录")
                        })
                    }
                })
            },
            go_show_video_div:function(){
                if(html_data.goods_info.video_id){
                    html_data.show_video_div = !html_data.show_video_div;
                    if(!html_data.show_video_div){
                        setTimeout(function () {
                            var elem = document.getElementById('jiaodiantu');
                            if(!elem){
                                return;
                            }
                            $(".xiaoyuandian li").eq(0).addClass("cur");
                            window.mySwipe = new Swipe(elem, {
                                //1秒
                                // auto: 1000,
                                callback: function (index, element) {
                                    $(".xiaoyuandian li").eq(index).addClass("cur").siblings().removeClass("cur");
                                }
                            });
                        }, 200);
                    }
                }
            },
            go_share_info: function () {
                window.location.href="share_info.html?goods_id="+GetQueryString("goods_id");
            },
            share_goods:function(){
                Magiclamp.mcAlert("提示", "请点击右上角菜单进行分享。");
            },

            tuijian:function(goods){
                api.lgc.create_goods_tuijian({goods_id:goods.id}).then(function (value) {
                    Magiclamp.mcAlert("提示", "已经收录我的分享推荐。");
                })

            },

            quick_create_order: function ($event) {
                if (html_data.is_login) {
                    var _this = $($event);
                    _this.css('pointer-events', 'none');
                    Magiclamp.midLoadingShow('处理中...');
                    if(html_data.pro_user_id){
                        if(parseInt(html_data.pro_user_id).toString()!=html_data.pro_user_id.toString()){
                            html_data.pro_user_id = "";
                        }
                    }else{
                        html_data.pro_user_id = "";
                    }


                    api.lorder.quick_create_order({
                        goods_id: html_data.goods_info.id,
                        pro_user_id:html_data.pro_user_id,
                        num: parseInt($("#count-sum").html())
                    }).then(function (data) {
                        Magiclamp.midLoadingHide();
                        //Magiclamp.mcAlert('', data.message);

                        if(data.result.is_need_pay_order) {
                            Magiclamp.mcConfirm("提示", data.message, null, function () {
                                client_storage("page", "tab_order");
                                location.href = 'home.html';
                            });
                            // 记录直接购买的记录
                            var from = GetQueryString("frompage");
                            if(from=="news_share_link"){
                                api.an.save_news_order({goods_id:GetQueryString("goods_id"), news_id:GetQueryString("news_id")}).then(function () {
                                    console.log("保存链接进入购买记录")
                                })
                            }else if(from=="goods_share_link"){
                                api.an.save_goods_order({goods_id:GetQueryString("goods_id")}).then(function () {
                                    console.log("保存链接进入购买记录")
                                })
                            }
                        }else if(data.result.is_need_pay_order==false&&data.result.is_new_goods){
                            api.sys.get_sys_data({flag: "buy_repeat_new_goods_url"}).then(function (value) {
                                // location.href = value.result.data;
                                Magiclamp.mcConfirm4("提示", "您已经购买过【新用户商品】，欢迎前往购买其他商品。", value.result.data, function () {
                                }, function () {

                                })
                            });

                        }else{
                            location.href = 'pay.html?payorder_id=' + data.result.id;
                        }



                    }, function (data) {
                        Magiclamp.midLoadingHide();
                        Magiclamp.midToast('fail', '购买失败，请重试', function () {
                            var _this = $($event);
                            _this.css('pointer-events', 'auto');
                        });
                    });
                } else {
                    login_mogu(function () {
                        html_data.is_login = true;
                        app.get_cart_goods_num();
                    }, "goods", GetQueryString("goods_id"), true);
                }

            },
            select_img: function (img) {
                html_data.selected_img = img.url;
            },
            open_cart: function () {
                client_storage("page", 'tab_cart');
                location.href = 'home.html';
            },

            go_to_programe: function (program_id, show_type) {
                if(!show_type){
                    show_type = ''
                }
                var phone_type_obj = phone_type();
                if (phone_type_obj.is_wx) {
                    if (phone_type_obj.is_ios) {
                        location.href = 'play_ios.html?type=ios&program_id=' + program_id+"&show="+show_type;
                    } else if (phone_type_obj.is_android) {
                        location.href = 'play_android.html?type=android&program_id=' + program_id+"&show="+show_type;
                    } else {
                        // 非android 和 ios 手机上的微信浏览器
                    }
                } else {
                    if (phone_type_obj.is_ios) {
                        location.href = 'play_ios.html?type=ios&program_id=' + program_id+"&show="+show_type;
                    } else if (phone_type_obj.is_android) {
                        location.href = 'play_android.html?type=android&program_id=' + program_id+"&show="+show_type;
                    } else {
                        // 非 ios 和 android的 系统的其他浏览器
                    }
                }
                // api.lprogram.get_live_program({live_program_id:liveprograme_id}).then(function (data) {
                //     ttjd.goto_liveprograme_page(null, null, liveprograme_id, JSON.stringify(data.result));
                // }, function (data) {
                //     Magiclamp.midToast('fail', '请稍后再试');
                // });
            },
            show_video:function(){
                html_data.show_video_img =!html_data.show_video_img;
                setTimeout(function () {
                    document.getElementById("goods_video").play();
                },200)
            },
            pause_video:function(){
                html_data.show_video_img =!html_data.show_video_img;

            },
            go_goodsstroe:function(){
                var phone_dict = phone_type();
                var phone = 'android';
                if (phone_dict.is_ios) {
                    phone = 'ios';
                }
                var goods = html_data.goods_info;
                if(!goods.liveprogram_id){
                    goods.liveprogram_id = "";
                }
                // location.href = 'goods.html?goods_id='+goods_id;
                if(goods.goodsstore_id){
                    location.href = 'play_' + phone + '.html?&show=goods&type=' + phone + '&program_id=' + goods.liveprogram_id + "&goodsstore_id="+goods.goodsstore_id+"&t=" + new Date().getTime();
                }else{
                    location.href = 'play_' + phone + '.html?&show=goods&type=' + phone + '&program_id=' + goods.liveprogram_id + "&goodsstore_id=0&t=" + new Date().getTime();
                }
            },
            go_goods_detail: function (goods_id) {
                location.href = 'goods.html?goods_id=' + goods_id
            },
            page_back: function () {
                baseConfig.page_back();
                setTimeout(function () {
                    app.go_to_programe(html_data.goods_info.liveprogram_id, "goods");
                }, 200);
            }
        }
    });


    html_data.sessionid = GetQueryString('sessionid');
    if (html_data.sessionid) {
        html_data.sessionid_q = "sessionid=" + html_data.sessionid;
        client_storage('sessionid', html_data.sessionid);
    }

    Magiclamp.quantityCtrl();

    api.lgoods.get_goods({goods_id: GetQueryString("goods_id")}).then(function (data) {

        if (data.result.files_json) {
            data.result.files_json = JSON.parse(data.result.files_json);
        } else {
            data.result.files_json = [];
        }
        if (data.result.desc_files_json) {
            data.result.desc_files_json = JSON.parse(data.result.desc_files_json);
        } else {
            data.result.desc_files_json = [];
        }

        html_data.goods_info = data.result;
        if(html_data.goods_info.video_id){
            html_data.show_video_div = true;
        }else{
            html_data.show_video_div = false;
        }
        if (data.result.files_json.length > 0) {
            html_data.selected_img = data.result.files_json[0]['url'];
        }
        if(wx_has_ready){
            api.sys.create_sharelink({goods_id:GetQueryString("goods_id")}).then(function (value) {
                var url = value.result.url + "&frompage=goods_share_link";;
                // var img_url = html_data.selected_img;
                // if (!img_url) {
                //     img_url = 'http://www.mmggoo.com/static/weixin/img2/icon.png';
                // }
                wx.onMenuShareTimeline({
                    title: '一起买，你能优惠'+price_filter(html_data.goods_info.x_price)+'元，我也能再省'+price_filter(html_data.goods_info.y_price)+'元', // 分享标题
                    link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: html_data.selected_img, // 分享图标
                    success: function (res) {
                        // 用户确认分享后执行的回调函数
                        api.an.save_goods_shared({goods_id:html_data.goods_info.id}).then(function () {
                            console.log("记录分享商品链接成功")
                        });
                        console.log(res);
                    },
                    cancel: function (res) {
                        // 用户取消分享后执行的回调函数
                        console.log(res);
                    }
                });
                wx.onMenuShareAppMessage({
                    title: '华迅直购--' + html_data.goods_info.name, // 分享标题
                    desc: '分享给你，一起买，你能优惠'+price_filter(html_data.goods_info.x_price)+'元，我也能再省'+price_filter(html_data.goods_info.y_price)+'元', // 分享描述
                    link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: html_data.selected_img, // 分享图标
                    type: '', // 分享类型,music、video或link，不填默认为link
                    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                    success: function (res) {
                        // 用户确认分享后执行的回调函数
                        api.an.save_goods_shared({goods_id:html_data.goods_info.id}).then(function () {
                            console.log("记录分享商品链接成功")
                        });
                        console.log(res);
                    },
                    cancel: function (res) {
                        // 用户取消分享后执行的回调函数
                        console.log(res);
                    }
                });

            });
        }

        setTimeout(function () {
            var elem = document.getElementById('jiaodiantu');
            if(!elem){
                return;
            }
            $(".xiaoyuandian li").eq(0).addClass("cur");
            window.mySwipe = new Swipe(elem, {
                //1秒
                // auto: 1000,
                callback: function (index, element) {
                    $(".xiaoyuandian li").eq(index).addClass("cur").siblings().removeClass("cur");
                }
            });
        }, 1000);

        api.lgoods.query_hot_goods_by_goods_type_list({goodstype_id:html_data.goods_info.goodstype_id}).then(function (value) {
            html_data.goods_list = value.result.list;
        })
    });

    // 不显示同活动下其他商品，则不需要调用此接口
    // app.query_goods_by_liveprograme();

    login_mogu(function () {
        html_data.is_login = true;
        app.get_cart_goods_num();

        var share_id = GetQueryString("share_id");
        var share_user_id = GetQueryString("share_user_id");
        var from = GetQueryString("frompage");

        if(from=="news_share_link"||from=="goods_share_link"){
            var from_user_id = 0;
            if(share_user_id&&share_user_id.length>0){
                from_user_id = share_user_id;
            }
            api.an.save_goods_clicked({goods_id:GetQueryString("goods_id"),from_user_id:from_user_id}).then(function () {
                console.log("保存链接进入记录")
            })
        }


        if(share_id&&share_id.length>0){
            api.sys.set_share_user({i:share_id}).then(function (value) {
            })
        }else{
            if(share_user_id&&share_user_id.length>0){
                api.sys.set_share_user_by_user({from_user_id:share_user_id}).then(function (value) {
                })
            }
        }

        api.lorder.get_express_price_by_location({goods_id:GetQueryString("goods_id")}).then(function (value2) {
            html_data.is_send = true;
            html_data.send_address = value2.result.address;
            html_data.send_price = value2.result.price;
        })

        api.sys.wx_js_sdk_info({url:location.href}).then(function (data) {
            api.sys.create_sharelink({goods_id:GetQueryString("goods_id")}).then(function (value) {
                api.lgoods.create_together_price_share({goods_id:GetQueryString("goods_id")}).then(function (together_value) {
                    var url = value.result.url + "&frompage=goods_share_link&together_id="+together_value.result.together_id;
                    try {

                        wx.config({
                            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                            appId: 'wxd78bb63115a11db4', // 必填，公众号的唯一标识
                            timestamp: data.result.timestamp, // 必填，生成签名的时间戳
                            nonceStr: data.result.noncestr, // 必填，生成签名的随机串
                            signature: data.result.signature,// 必填，签名
                            jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 必填，需要使用的JS接口列表
                        });
                        wx.error(function (res) {
                            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
                            console.log(res);
                        });
                        wx.ready(function(){
                            wx_has_ready = true;
                            if(html_data.goods_info.id){
                                // var img_url = html_data.selected_img;
                                // if(!img_url){
                                //     img_url = 'http://www.mmggoo.com/static/weixin/img2/icon.png';
                                // }
                                wx.onMenuShareTimeline({
                                    title: '一起买，你能优惠'+price_filter(html_data.goods_info.x_price)+'元，我也能再省'+price_filter(html_data.goods_info.y_price)+'元', // 分享标题
                                    link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                    imgUrl: html_data.selected_img, // 分享图标
                                    success: function (res) {
                                        // 用户确认分享后执行的回调函数
                                        api.an.save_goods_shared({goods_id:html_data.goods_info.id}).then(function () {
                                            console.log("记录分享商品链接成功")
                                        });
                                        console.log(res);
                                    },
                                    cancel: function (res) {
                                        // 用户取消分享后执行的回调函数
                                        console.log(res);
                                    }
                                });
                                wx.onMenuShareAppMessage({
                                    title: '华迅直购--'+html_data.goods_info.name, // 分享标题
                                    desc: '分享给你，一起买，你能优惠'+price_filter(html_data.goods_info.x_price)+'元，我也能再省'+price_filter(html_data.goods_info.y_price)+'元', // 分享描述
                                    link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                    imgUrl: html_data.selected_img, // 分享图标
                                    type: '', // 分享类型,music、video或link，不填默认为link
                                    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                                    success: function (res) {
                                        // 用户确认分享后执行的回调函数
                                        api.an.save_goods_shared({goods_id:html_data.goods_info.id}).then(function () {
                                            console.log("记录分享商品链接成功")
                                        });
                                        console.log(res);
                                    },
                                    cancel: function (res) {
                                        // 用户取消分享后执行的回调函数
                                        console.log(res);
                                    }
                                });


                            }

                        });



                    } catch (res) {
                        console.log(res);
                    }
                });

            })

        })

        var together_id = GetQueryString("together_id");
        if(together_id){
            api.lgoods.check_together_price_share({together_id:together_id}).then(function (check_value) {
                if(!check_value.result.has_visit){
                    api.lgoods.get_together_price_detail_info({together_id:together_id}).then(function (value) {
                        if(value.result.has_join){
                            ger_together_info_detail();
                            return;
                        }
                        var msg = "<span style='color: red;font-weight: bold'>"+value.result.buyer__realname+"</span>约您一起买，一起减。<br/>";
                        msg += "你能优惠"+"<span style='color: red;font-weight: bold'>"+price_filter(value.result.goods__x_price)+"元</span>，我也能再省";
                        msg += "<span style='color: red;font-weight: bold'>"+price_filter(value.result.goods__z_price)+"元</span>。你愿意一起买吗？";
                        Magiclamp.mcConfirm5("有人约你", msg, function () {
                            ger_together_info_detail();
                        }, function () {
                            // 调用参与
                            api.lgoods.join_together_price_share({together_id:together_id}).then(function (join_value) {
                                ger_together_info_detail();
                            })
                        })
                    })
                }else{
                    ger_together_info_detail();
                }
            })

        }else{
            ger_together_info_detail();
        }


    }, "goods", GetQueryString("goods_id"), true);


    function ger_together_info_detail() {
        api.lgoods.get_together_price_share_info({goods_id:GetQueryString("goods_id")}).then(function (value) {
            html_data.together_goods_info = value.result;
        })
    }


    //活动
    var actImgUrl = $('#activity-act_img').val();
    var actTitle = $('#activity-act_title').val();
    var actTxt = $('#activity-act_desc').val();
    var actId = $('#activity-id').val();
    var actIdcookie = Magiclamp.getCookie('actId' + actId);
    if (actIdcookie != 1 && actId > 0) {
        Magiclamp.mcActPop(actImgUrl, actTitle, actTxt, function () {
            Magiclamp.setCookie('actId' + actId, 1);
            location.href = '/account/user/register';
        }, function () {
            Magiclamp.setCookie('actId' + actId, 1);
        });
    }
    /*召唤前台送货代码*/
    if (haserr > 0) {
        if (haserr === 3) {
            Magiclamp.hasError(3, telfront);
        } else if (haserr === 4) {
            Magiclamp.hasError(4, telfront);
        }

        if (dnurl.length > 1) {
            Magiclamp.noticeShow(dnurl);
        }
    }


    //猜你喜欢动态计算总价
    like_total_price();

    function like_total_price() {
        var total_money = 0;
        $('.like-price-value').each(function (i, obj) {
            if ($(obj).prev().is(":checked")) {
                total_money += parseInt($(obj).val());
            }
        });
        total_money = total_money / 100;
        $("#like-price-total").html(total_money.toFixed(2));
    }

    $(".like-checkbox").on('click', function () {
        like_total_price();
    });


    /**
     *神灯商品和店内商品点击加载更多方法
     * @param obj 获取更多按钮
     * @param listWrap 填充的列表  神灯列表“$('.sd-goods')”和“店内"$('.dn-goods')"
     */
    var listGetMore = function (obj, listWrap) {
        var pageNum = obj.data('page');
        var getUrl = obj.data('href') + pageNum;
        var pdata = {};
        Magiclamp.listLoad(obj);
        Magiclamp.mcAjax(getUrl, "post", pdata, function (dataBack) {
                //生成html
                var html = '';
                if (dataBack.data) {
                    dataBack.data.forEach(function (tmp) {
                        html += '<li>';
                        html += '<a href="' + tmp.url + '" class="img-wrap" >';
                        html += '<img data-src="' + tmp.preimg + '" src="/img/gray.gif">';
                        html += '</a>';
                        html += '<p class="g-l-name">';
                        html += tmp.goodstitle;
                        html += '</p>';
                        html += '<p class="g-l-price">';
                        html += '<span>￥</span>';
                        html += '<span class="price">' + ((tmp.price / 100 ).toFixed(2)) + '</span>';
                        html += '</p>';
                        html += '</li>';
                    })
                }
                //插入ul
                listWrap.find('ul').append(html);
                Magiclamp.listLoadGet(obj, '加载更多', 'auto');
                Magiclamp.imgSrc();
                obj.data('page', Number(pageNum) + 1);
                //如果数据少于9条,说明已加载全部
                if (dataBack.data.length < 9) {
                    Magiclamp.listLoadGet(obj, '已加载全部', 'none');
                    return false;
                }
            }, function (databack) {
                Magiclamp.listLoadGet(obj, databack.message, 'none');
            }, true
        );
    };

    //tab-bar增加class
    Magiclamp.tabAddCls('self_service');


});

